﻿#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <cstring>
#include <cstdlib>

class Client
{
public:
    Client(std::string server_ip, uint16_t server_port)
        :_sockfd(-1)
        , _server_ip(server_ip)
        , _server_port(server_port)
    {}

    bool init()
    {
        //创建套接字

        _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        if (_sockfd < 0)
        {
            std::cerr << "socket error" << std::endl;
            return false;
        }
        return true;
    }


    void start()
    {
        char buffer[1024];
        struct sockaddr_in server;
        memset(&server, '\0', sizeof(server));
        //协议家族
        server.sin_family = AF_INET;
        //端口号
        server.sin_port = htons(_server_port);
        //IP
        server.sin_addr.s_addr = inet_addr(_server_ip.c_str());
        //发送
        while (1)
        {
            std::cout << "Please enter# ";
            std::cin.getline(buffer, sizeof(buffer));
            sendto(_sockfd, buffer, 1024, 0, (struct sockaddr*)&server, (socklen_t)sizeof(struct sockaddr_in));
        }
    }

    ~Client()
    {
        if (_sockfd >= 0)
        {
            close(_sockfd);
        }
    }
private:
    uint16_t _server_port;
    std::string _server_ip;
    int _sockfd;
};